<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="商户ID" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入商户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商户名称" prop="infoName">
        <el-input v-model="queryParams.infoName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="infoType">
        <el-select v-model="queryParams.infoType" clearable placeholder="请选择商户类型" filterable>
          <el-option v-for="(item, i) in extData.sourceList || []" :key="i" :label="item.key"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商务信息" prop="ownerId" filterable>
        <el-select v-model="queryParams.ownerId" clearable placeholder="请选择机构商务" filterable>
          <el-option v-for="(item, i) in extData.ownerInfoList || []" :key="i" :label="item.nickname"
            :value="item.userId">
          </el-option>
        </el-select>.
        <div class="."></div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['merchant:baseInfo:add']">开户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-data-analysis" size="small" @click="handle"
          v-hasPermi="['merchant:pushInfo:count']">推送折线图</el-button>
      </el-col>
      <el-col :span="1.5" class="centered-link">
        <el-link @click.prevent="copyToClipboard(extData.shareUrl)">
          开户链接： {{ extData.shareUrl }}
        </el-link>
      </el-col>

      <el-col :span="4">
  <el-tag >红色背景：余额不足,机构任务没开   ||  紫色背景：该机构为单推 </el-tag>
</el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>



    <el-table :row-class-name="tableRowClassName" v-loading="loading" :data="baseInfoList">
      <el-table-column label="商户ID" align="center" prop="id" />
      <el-table-column label="商户信息（权重）" align="center" :width="250">
        <template slot-scope="scope">
          <span @click="$router.push(`/merchant/log?infoId=${scope.row.id}`)">
            {{ scope.row.infoName }}
            <span v-if="scope.row.priceType === '2'" style="color: red;">CPS/{{ scope.row.typeRate }}</span>
          </span>
          <span
            :style="{ color: scope.row.infoType === 'API' ? 'red' : scope.row.infoType === 'CRM' ? 'blue' : 'green' }">
            [{{ scope.row.infoType }}]
          </span>
          <span style="color: rgba(226, 17, 17, 0.5)"> [{{ scope.row.sortWeight }}]</span>
          <span v-if="scope.row.riskFlag === 1" style="color: rgba(226, 17, 17, 0.904)"> [RISK]</span>
        </template>
      </el-table-column>
      <el-table-column label="描述信息" align="center" prop="descInfo" width="100" />
      <el-table-column label="展示信息" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showCompanyInfo(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="登陆信息" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showLoginInfo(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="客户经理" align="center" prop="ownerName" /> -->
      <el-table-column label="商务信息" align="center" prop="ownerName" width="120">
        <template slot-scope="scope">
          {{ scope.row.ownerName }} [ {{ scope.row.ownerId }} ]
        </template>
      </el-table-column>
      <el-table-column label="账户余额" align="center" prop="totalAmount" />
      <!-- <el-table-column label="每日推送数量" align="center" prop="pushNumber" /> -->
      <el-table-column label="在线任务" align="center" prop="onlineTaskNumber" />
       <el-table-column label="流量比例" align="center" prop="sourceDataScale" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-hasPermi="['merchant:baseInfo:updateStatus']" v-model="scope.row.status" :active-value="1"
            :inactive-value="0" @change="handleStatusChange(scope.row, $event)"></el-switch>
          <span :style="{ color: scope.row.status === 0 ? 'red' : 'green' }">{{ scope.row.status === 0 ? '关' : '开'
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="多推" align="center" prop="singlePushFlag">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.singlePushFlag" :active-value="1"
            :inactive-value="0" @change="handleStatusChange1(scope.row, $event)"></el-switch>
          <span :style="{ color: scope.row.singlePushFlag === 0 ? 'red' : 'green' }">{{ scope.row.singlePushFlag === 0 ? '关' : '开'
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="复推" align="center" prop="statusAgain">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.statusAgain" :active-value="1"
                     :inactive-value="0" @change="handleStatusChange2(scope.row, $event)"></el-switch>
          <span :style="{ color: scope.row.statusAgain === 0 ? 'red' : 'green' }">{{ scope.row.statusAgain === 0 ? '关' : '开'
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="$router.push(`/merchant/taskinfo?id=${scope.row.id}`)">任务</el-button>
        </template>
      </el-table-column>
      <el-table-column label="账单" align="center">
        <template slot-scope="scope">
          <el-button type="text"
            @click="$router.push(`/merchant/merchantInfoHis?accountId=${scope.row.id}`)">账单</el-button>
        </template>
      </el-table-column>
      <el-table-column label="数据" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="redirectToInfo(scope.row)">数据</el-button>
        </template>
      </el-table-column>
      <el-table-column label="成员" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.infoType === 'CRM'">
            <el-button type="text" @click="$router.push(`/merchant/userInfo?infoId=${scope.row.id}`)">成员</el-button>
          </span>
          <span v-else>--
          </span>
        </template>
      </el-table-column>

      <el-table-column label="开户时间" align="center" width="150">
        <template slot-scope="scope">
          {{ formatTimestamp(scope.row.createTime) }}
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:baseInfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateKey(scope.row)"
            v-if="scope.row.infoType != 'CRM'" v-hasPermi="['merchant:baseInfo:edit']">密钥</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:baseInfo:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 查看弹窗 -->
    <el-dialog :visible.sync="loginInfoDialogVisible" width="400px" append-to-body>
      <div class="card-container">
        <!-- <div class="dialog-content"> -->
        <div class="info-item">
          <span class="info-label">商户名称:</span>
          <span class="info-value">{{ loginInfo.infoName }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">登录账户:</span>
          <span class="info-value">{{ loginInfo.adminName }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">登录密码:</span>
          <span class="info-value">{{ loginInfo.adminPwd }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">登录地址:</span>
          <span class="info-value">{{ loginInfo.loginAddress }}</span>
        </div>
        <!-- </div> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="copyContent">一键复制</el-button>
        <el-button @click="cancel">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 公司信息弹窗 -->
    <el-dialog :visible.sync="companyInfoDialogVisible" width="400px" append-to-body>
      <div class="card-container">
        <!-- <div class="dialog-content"> -->
        <div class="info-item">
          <span class="info-label">展示名称:</span>
          <span class="info-value">{{ companyInfo.companyName }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">标题:</span>
          <span class="info-value">{{ companyInfo.companyTitle }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">副标题:</span>
          <span class="info-value">{{ companyInfo.companySubTitle }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">产品logo:</span>
          <span class="info-value">
            <ImagePreview v-if="!!companyInfo.companyLogo" :src="companyInfo.companyLogo" :width="70" :height="80" />
          </span>
        </div>

        <div class="info-item">
          <span class="info-label">最大金额:</span>
          <span class="info-value">{{ companyInfo.maxLoanAmount }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">最大利率:</span>
          <span class="info-value">{{ companyInfo.maxRate }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">最小利率:</span>
          <span class="info-value">{{ companyInfo.minRate }}</span>
        </div>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </span>
    </el-dialog>


    <!-- 添加或修改商户基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="机构名称" prop="infoName">
          <el-input v-model="form.infoName" placeholder="请输入机构名称" :maxlength="15" show-word-limit />
        </el-form-item>
        <el-form-item label="描述" prop="descInfo">
          <el-input v-model="form.descInfo" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="机构类型" prop="infoType">
          <el-select v-model="form.infoType" clearable placeholder="请选择商户类型" filterable>
            <el-option v-for="(item, i) in extData.sourceList || []" :key="i" :label="item.key"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-tooltip class="item" effect="dark" content="可推送的线索（apib/apis）量是渠道（app/h5）量的比例。比如：该值为0.5时，当渠道量推送为2个时，才可以推送1个线索量" placement="top">
            <el-form-item label="流量比例" prop="sourceDataScale" >
              <el-input v-model="form.sourceDataScale" placeholder="请输入流量比例" />
            </el-form-item>
        </el-tooltip>

        <el-form-item label="价格类型" prop="priceType">
          <el-select v-model="form.priceType" placeholder="请选择价格类型">
            <el-option label="固定价格" value="1"></el-option>
            <el-option label="分润价格" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-tooltip v-if="form.priceType === '2'" class="item" effect="dark" content="例如：28分成就填写0.8" placement="top">
          <el-form-item label="分润比率" prop="typeRate">
            <el-input v-model="form.typeRate" placeholder="请输入分润比率" />
          </el-form-item>
        </el-tooltip>

        <el-tooltip v-if="form.priceType === '2'" class="item" effect="dark" content="限制该机构的返回最低价格，和润后进行比较"
          placement="top">
          <el-form-item label="最低价格" prop="checkMinPrice">
            <el-input v-model.number="form.checkMinPrice" placeholder="请输入分润比率" type="number" :min="0" />
          </el-form-item>
        </el-tooltip>

        <!-- <el-form-item label="推送数量" prop="pushNumber">
          <el-input v-model="form.pushNumber" placeholder="请输入推送数量" type="number" min="0" />
        </el-form-item> -->
        <el-form-item label="商务姓名" prop="ownerId">
          <el-select v-model="form.ownerId" style="width: 100%;" placeholder="请选择机构商务">
            <el-option v-for="(item, i) in extData.ownerInfoList || []" :key="i" :label="item.nickname"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="撞库类型" prop="checkType">
          <el-select v-model="form.checkType" placeholder="请选择撞库类型">
            <el-option v-for="(item, i) in extData.checkTypeList || []" :key="i" :label="item.key"
                       :value="item.value"></el-option>
          </el-select>
          <br>
          <span style="color: red">注意：撞库类型不可多选，默认为全类型撞库</span>
        </el-form-item>

        <el-form-item label="推荐语" prop="companyTitle">
          <el-input v-model="form.companyTitle" placeholder="请输入推荐语" />
        </el-form-item>
        <el-form-item label="展示名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入展示名称" />
        </el-form-item>

        <el-form-item label="Slogan" prop="sublabelInfo">
          <el-input v-model="form.sublabelInfo" placeholder="请输入Slogan" />
        </el-form-item>

        <el-form-item label="公司名称" prop="companySubTitle">
          <el-input v-model="form.companySubTitle" placeholder="请输入公司名称" />
        </el-form-item>
         <el-form-item label="官方电话" prop="companyPhone">
          <el-input v-model="form.companyPhone" placeholder="请输入官方电话" />
        </el-form-item>
        <!--<el-form-item label="公司联系人" prop="companyUser">
          <el-input v-model="form.companyUser" placeholder="请输入公司联系人" />
        </el-form-item>-->

        <el-form-item label="产品logo" prop="companyLogo">
          <ImageUpload v-model="form.companyLogo" :limit="1" bizType="MERCHANTLOGO" type="cos" />
        </el-form-item>

        <el-form-item label="最高额度(元)" prop="maxLoanAmount">
          <el-input v-model="form.maxLoanAmount" placeholder="请输入最高额度" />
        </el-form-item>

        <el-form-item label="年化率(%)" prop="minRate">
          <el-input v-model="form.minRate" placeholder="请输入年化率" />
        </el-form-item>

<!--        <el-form-item label="最小利率" prop="minRate">-->
<!--          <el-input v-model="form.minRate" placeholder="请输入最小利率" />-->
<!--        </el-form-item>-->

        <el-form-item label="放款速度(小时)" prop="speed">
          <el-input v-model="form.speed" placeholder="请输入放款速度" />
        </el-form-item>
        <el-form-item label="贷款期限" prop="loanTime">
          <el-input v-model="form.loanTime" placeholder="请输入贷款期限" />
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改商户基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="openKey" width="600px" append-to-body>
      <el-form ref="formKey" :model="formKey" :rules="rules" label-width="80px">

        <el-form-item label="factoryType" prop="factoryType">
          <el-input v-model="formKey.factoryType" />
        </el-form-item>

        <el-form-item label="是否授权" prop="approveFlag">
          <el-select v-model="formKey.approveFlag" placeholder="请选择跳转类型">
            <el-option label="跳转授权" value="1"></el-option>
            <el-option label="不跳转" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="展示位置" prop="showPosition">
          <el-select v-model="formKey.showPosition" style="width: 100%;" placeholder="请选择展示位置">
            <el-option v-for="(item, i) in extData.showPositionList || []" :key="i" :label="item.key"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序权重" prop="sortWeight">
          <el-input-number v-model="formKey.sortWeight" :min="1" :max="500" label="请输入排序权重"></el-input-number>
        </el-form-item>

        <el-form-item label="apiCode" prop="apiCode">
          <el-input v-model="formKey.apiCode" />
        </el-form-item>

        <el-form-item label="apiKey" prop="apiKey">
          <el-input v-model="formKey.apiKey" />
        </el-form-item>

        <el-form-item label="apiSecret" prop="apiSecret">
          <el-input v-model="formKey.apiSecret" />
        </el-form-item>

        <el-form-item label="apiPubKey" prop="apiPubKey">
          <el-input type="textarea" v-model="formKey.apiPubKey" />
        </el-form-item>

        <el-form-item label="apiPriKey" prop="apiPriKey">
          <el-input type="textarea" v-model="formKey.apiPriKey" />
        </el-form-item>

        <el-form-item label="apiCheckUrl" prop="apiCheckUrl">
          <el-input v-model="formKey.apiCheckUrl" />
        </el-form-item>

        <el-form-item label="apiRegisterUrl" prop="apiRegisterUrl">
          <el-input v-model="formKey.apiRegisterUrl" />
        </el-form-item>

        <el-form-item label="apiQueryUrl" prop="apiQueryUrl">
          <el-input v-model="formKey.apiQueryUrl" />
        </el-form-item>

        <el-form-item label="apiProtocolUrl" prop="apiProtocolUrl">
          <el-input v-model="formKey.apiProtocolUrl" />
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormKey">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <Count ref="CountRef" />

  </div>
</template>

<style>
.centered-link {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 5px;
}

.red-text {
  color: red;
}

.purple-row {
  background-color: #dfd1eb !important;  /* 紫色背景 */
}

.blue-text {
  color: blue;
}

.el-table .on-row {
  background: #fad8d8;
}

.dialog-content {
  padding: 20px;
}

.info-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.info-value {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-content {
  padding: 20px;
  border-radius: 5px;
}

.dialog-title {
  text-align: center;
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.dialog-divider {
  border: 1px solid #ccc;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.info-label {
  font-weight: bold;
  color: #333;
  flex: 1;
}

.info-value {
  flex: 2;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}


.card-container {
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.info-item {
  margin-bottom: 10px;
}

.info-label {
  font-weight: bold;
}


.large-confirm-box .el-message-box {
  width: 500px; /* 增大弹窗宽度 */
}

.large-confirm-box .el-message-box__title {
  font-size: 24px; /* 提示框标题字体变大 */
}

.large-confirm-box .el-message-box__content {
  font-size: 18px; /* 提示框内容字体变大 */
}

/* 自定义按钮样式 */
.custom-confirm-button {
  background-color: #e74c3c; /* 确定按钮的红色背景 */
  font-size: 18px; /* 调整按钮的字体大小 */
  color: white; /* 按钮文字为白色 */
  padding: 10px 20px; /* 按钮大小调整 */
}

.custom-cancel-button {
  background-color: #7f8c8d; /* 取消按钮的灰色背景 */
  font-size: 18px; /* 调整按钮的字体大小 */
  color: white; /* 按钮文字为白色 */
  padding: 10px 20px; /* 按钮大小调整 */
}
</style>



<script>
import {
  listBaseInfo,
  getBaseInfo,
  delBaseInfo,
  addBaseInfo,
  updateBaseInfo,
  changeUserStatus,
  baseInfoExtData
} from "@/api/merchant/baseInfo";
import copy from 'copy-to-clipboard';
import { isHavePermission } from '@/directive/permission/hasPermi'
import { isMobile } from 'mobile-device-detect';
import Count from './echars/count.vue'

export default {
  components: {
    Count
  },
  name: "BaseInfo",
  data() {
    return {
      loginInfoDialogVisible: false, // 控制弹窗显示/隐藏
      // loginAddress: process.env.VUE_APP_LOGIN_URL,
      loginInfo: {
        infoName: '',
        adminName: '',
        adminPwd: '',
        loginAddress: process.env.VUE_APP_LOGIN_URL
      },
      companyInfoDialogVisible: false,
      companyInfo: {
        companyName: '',
        companySubTitle: '',
        companyTitle: '',

        companyLogo: '',
        maxLoanAmount: '',
        maxRate: '',
        minRate: '',

      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: !isMobile,
      // 总条数
      total: 0,
      // 商户基本信息表格数据
      baseInfoList: [],
      shareUrl: null,
      extData: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        infoName: null,
        infoType: null,
        descInfo: null,
        ownerId: null,
        ownerName: null,
        companyName: null,
        companyUser: null,
        companyPhone: null,
        pushNumber: null,
        riskFlag: null,
        status: null,
        deptId: null,
        creator: null,
        updater: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "展示名称不能为空", trigger: "change" }
        ],
        sublabelInfo: [
          { required: true, message: "Slogan不能为空", trigger: "change" }
        ],
        companySubTitle: [
          { required: true, message: "展示公司名称不能为空", trigger: "change" }
        ],
        maxLoanAmount: [
          { required: true, message: "最高额度不能为空", trigger: "change" }
        ],
        maxRate: [
          { required: true, message: "最大利率不能为空", trigger: "change" }
        ],
        minRate: [
          { required: true, message: "年化率不能为空", trigger: "change" }
        ],
        loanTime: [
          { required: true, message: "贷款期限不能为空", trigger: "change" }
        ],
        speed: [
          { required: true, message: "放款速度不能为空", trigger: "change" }
        ],
      },
      // 密钥相关信息
      formKey: {},
      titleKey: "",
      openKey: false,
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    tableRowClassName({ row }) {
    // 判断是否满足已有的条件
    if ((row.onlineTaskNumber === 0 && row.status === 1) || (row.status === 1 && row.totalAmount < 1000)) {
      return 'on-row';
    }
    if (row.singlePushFlag === 0) {
      return 'purple-row';
    }
    return '';
  },

    isHavePermission,
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },
    copyContent() {
      const contentToCopy = this.getDialogContent(); // 获取弹窗内容
      copy(contentToCopy, {
        format: 'text/plain'
      })
      this.$message.success('内容已成功复制！');
    },
    /**更改创建时间格式 */
    formatTimestamp(timestamp) {
      if (!timestamp) {
        return '';
      }
      const date = new Date(timestamp);
      const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      return formattedDate;
    },

    copyToClipboard(text) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success('复制成功');
        }).catch(err => {
          this.$message.error('复制失败');
        });
      } else {
        let textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.position = "fixed";  // avoid scrolling to bottom
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
          let successful = document.execCommand('copy');
          if (successful) {
            this.$message.success('复制成功');
          } else {
            this.$message.error('复制失败');
          }
        } catch (err) {
          this.$message.error('复制失败');
        }
        document.body.removeChild(textArea);
      }
    },

    getDialogContent() {
      const infoName = this.loginInfo.infoName;
      const adminName = this.loginInfo.adminName;
      const adminPwd = this.loginInfo.adminPwd;
      const loginAddress = this.loginInfo.loginAddress;
      // 格式化成文本
      const content = `机构名称: ${infoName}
登录账户: ${adminName}
登录密码: ${adminPwd}
登录地址: ${loginAddress} `
      return content;

    },
    /**数据跳转页面 */
    redirectToInfo(row) {
      if (row.infoType === 'CRM') {
        this.$router.push(`/merchant/crmpushInfo?infoId=${row.id}`);
      } else {
        this.$router.push(`/merchant/pushInfo?infoId=${row.id}`);
      }
    },
    /**展示卡片 */
    showLoginInfo(row) {
      this.loginInfoDialogVisible = true;
      this.loginInfo.infoName = row.infoName;
      this.loginInfo.adminName = row.adminName;
      this.loginInfo.adminPwd = row.adminPwd;
    },
    /**展示卡片 */
    showCompanyInfo(row) {
      this.companyInfoDialogVisible = true;
      this.companyInfo.companyName = row.companyName;
      this.companyInfo.companyTitle = row.companyTitle;
      this.companyInfo.companySubTitle = row.companySubTitle;
      this.companyInfo.companyLogo = row.companyLogo;
      this.companyInfo.maxLoanAmount = row.maxLoanAmount;
      this.companyInfo.maxRate = row.maxRate;
      this.companyInfo.minRate = row.minRate;
    },
    /** 查询商户基本信息列表 */
    getList() {
      this.loading = true;
      listBaseInfo(this.queryParams).then((response) => {
        this.baseInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 用户状态修改
    handleStatusChange(row, value) {
      let text = (+value) === 0 ? "停用" : "启用";
      changeUserStatus({ id: row.id, status: +value }).then(res => {
        this.$modal.msgSuccess(text + "成功");
        this.handleQuery();
      }).catch(() => {
        row.status = row.status == 0 ? 1 : 0;
      })
    },
    handleStatusChange2(row, value) {
      let text = (+value) === 0 ? "停用" : "启用";
      changeUserStatus({ id: row.id, statusAgain: +value }).then(res => {
        this.$modal.msgSuccess(text + "成功");
        this.handleQuery();
      }).catch(() => {
        row.statusAgain = row.statusAgain == 0 ? 1 : 0;
      })
    },
    handleStatusChange1(row, value) {
  if (+value === 0) {
    this.$confirm(
      '<strong style="font-size: 22px; color: red;">确定要修改为单推吗？修改后,变成竞价模式</strong><br><span style="font-size: 18px;">竞价模式：若同一时间内多家机构撞库成功，则价高者得，反之价低者不推送</span>',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        customClass: 'large-confirm-box',
        confirmButtonClass: 'custom-confirm-button',
        cancelButtonClass: 'custom-cancel-button',
        center: true
      }
    ).then(() => {
      // 如果用户点击了“确定”
      updateBaseInfo({ id: row.id, singlePushFlag: +value }).then(res => {
        this.$modal.msgSuccess('修改成功');
        this.handleQuery();
      }).catch(() => {
        row.singlePushFlag = row.singlePushFlag == 0 ? 1 : 0;
      });
    }).catch(() => {
      // 如果用户点击了“取消”，恢复原状态
      row.singlePushFlag = 1;
    });
  } else {
    // 启用时不需要弹出提示框
    updateBaseInfo({ id: row.id, singlePushFlag: +value }).then(res => {
      this.$modal.msgSuccess('启用成功');
      this.handleQuery();
    }).catch(() => {
      row.singlePushFlag = row.singlePushFlag == 0 ? 1 : 0;
    });
  }
}

,
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.loginInfoDialogVisible = false;
      this.companyInfoDialogVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyName: null,
        companyPhone: null,
        companyUser: null,
        descInfo: null,
        infoName: null,
        infoType: null,
        pushNumber: null,
        riskFlag: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户基本信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBaseInfo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商户基本信息";
      });
    },

    handle() {
      this.$refs.CountRef.show(this.queryParams)
    },
    /** 修改密钥 */
    handleUpdateKey(row) {
      this.reset();
      const id = row.id || this.ids;
      getBaseInfo(id).then((response) => {
        this.formKey = response.data;
        this.openKey = true;
        this.titlekey = "修改商户密钥信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        const postData = { ...this.form, ownerName: this.extData.ownerInfoList.find(item => item.userId == this.form.ownerId)?.nickname }
        if (valid) {
          if (this.form.id != null) {
            updateBaseInfo(postData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBaseInfo(postData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitFormKey() {
      this.$refs["formKey"].validate((valid) => {
        if (valid) {
          updateBaseInfo(this.formKey).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.openKey = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商户基本信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBaseInfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "merchant/baseInfo/export",
        {
          ...this.queryParams,
        },
        `baseInfo_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
